/**
 * Copyright (c) 2008, Keisuke Inoue, Syracuse Unviersity
 * All rights reserved.
 *
 */
package edu.syr.iis.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import edu.syr.iis.web.model.Adjacency;
import edu.syr.iis.web.model.AdjacencyManager;
import edu.syr.iis.web.model.DialogueAct;
import edu.syr.iis.web.model.DialogueActLabel;
import edu.syr.iis.web.model.DialogueActLabelManager;
import edu.syr.iis.web.model.DialogueActManager;
import edu.syr.iis.web.model.Message;
import edu.syr.iis.web.model.MessageManager;
import edu.syr.iis.web.model.User;
import edu.syr.iis.web.model.UserManager;
import edu.syr.iis.web.util.Key;

/**
 * @author kinoue
 *
 */
public class EnterDialogueActController extends SimpleFormController
{
	private static Log log = LogFactory.getLog(EnterDialogueActController.class);
	
	private DialogueActLabelManager dialogueActLabelManager = null;	
	private DialogueActManager dialogueActManager = null;
	private AdjacencyManager adjacencyManager = null;
	private MessageManager messageManager = null;
	private UserManager userManager = null;
	
	String referrer;

	private Message message;
	
	/**
	 * Returns a new instance of DialougeAct object if "daId" HTTP parameter 
	 * is not specified; otherwise returns the instance of the object in 
	 * the database matching the parameter.
	 */

	@Override
	protected Object formBackingObject(HttpServletRequest request)
	{
		log.debug("Entering: formBackingObject");

		referrer = request.getHeader("referer");

		DialogueAct da = null;
		User user = (User) request.getSession().getAttribute(Key.USER);

		if (request.getParameter(Key.DA_ID) != null
				&& request.getParameter(Key.DA_ID).trim().length() > 0) 
		{
			int id = Integer.parseInt(request.getParameter(Key.DA_ID));			
			da = dialogueActManager.getDialogueAct(id);
		} 
		else	
		{
			da = new DialogueAct();
			da.setUser(user);
		}
		
		
		da.setCreatedAt(new Date());

		if (request.getParameter(Key.MSG_ID) != null
				&& request.getParameter(Key.MSG_ID).trim().length() > 0) 
		{
			int messageId = Integer.parseInt(request.getParameter(Key.MSG_ID));
			message = messageManager.getMessage(messageId);
		}
			
		log.debug("Returning DialogueAct: " + "\n" + da.getLogString());
		
		return da;
	}   

	@Override
	protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception
	{		
		HashMap<String, Object> model = new HashMap<String, Object>();
		//DialogueActDimension dialogueActDimension = dialogueActDimensionManager.getDialogueActDimension() 
		model.put(Key.MSG, message);
		
		model.put(Key.USERS, userManager.getUsers());
		model.put(Key.ADJACENCIES, adjacencyManager.getAdjacencies());
		model.put(Key.DA_FUNCTIONS, dialogueActLabelManager.getDialogueActLabelsBySchemeAndDimension("Inoue", "Function"));
		model.put(Key.DA_DOMAINS, dialogueActLabelManager.getDialogueActLabelsBySchemeAndDimension("Inoue", "Domain"));
		
		return model;
	}

	
	@Override
	protected ModelAndView onSubmit(Object command)
	{
		DialogueAct da = (DialogueAct) command;
		da.setLastSavedAt(new Date());

		log.debug("Entering: onSubmit() with DialogueAct: \n" + da.getLogString());
		
		da.setMessage(message);		
		DialogueAct savedDa = dialogueActManager.saveDialogueAct(da);

		// The dialogue act is new, which means you need to add it to Message.
		if (savedDa.getDialogueActId() != da.getDialogueActId() && message != null) {
			log.debug("Updating Message....");
			message.addDialogueAct(savedDa);			
			messageManager.saveMessage(message);	
		}				
		
		log.debug("Saved Dialogue Act: \n " + da.getLogString());				
		log.debug("Exsiting: onSubmit()");
		
		if (referrer == null)
			return new ModelAndView("redirect:/cae/browsemessage.html?messageId=" + message.getMessageId());
		else
			return new ModelAndView("redirect:" + referrer);
	}
	
	public void setDialogueActManager(DialogueActManager dialogueActManager)
	{
		this.dialogueActManager = dialogueActManager;
	}

	
	public void setMessageManager(MessageManager messageManager) {
		this.messageManager = messageManager;
	}

	public void setDialogueActLabelManager(
			DialogueActLabelManager dialogueActLabelManager)
	{
		this.dialogueActLabelManager = dialogueActLabelManager;
	}

	
	public void setAdjacencyManager(AdjacencyManager adjacencyManager) {
		this.adjacencyManager = adjacencyManager;
	}

	
	
	public void setUserManager(UserManager userManager)
	{
	    this.userManager = userManager;
	}

	protected void initBinder(
			HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {

		System.out.println("Entering initBinder!");
		
		binder.registerCustomEditor(User.class, new UserPropertyEditor(userManager));
		binder.registerCustomEditor(Adjacency.class, new AdjacencyPropertyEditor(adjacencyManager));
		binder.registerCustomEditor(DialogueActLabel.class, new DialogueActLabelPropertyEditor(dialogueActLabelManager));
		binder.registerCustomEditor(DialogueAct.class, new DialogueActPropertyEditor(dialogueActManager));

	}



}
